package org.example.api.sink;

import org.apache.flink.api.common.serialization.SimpleStringSchema;
import org.apache.flink.streaming.api.datastream.DataStreamSource;
import org.apache.flink.streaming.api.datastream.SingleOutputStreamOperator;
import org.apache.flink.streaming.api.environment.StreamExecutionEnvironment;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaConsumer011;
import org.apache.flink.streaming.connectors.kafka.FlinkKafkaProducer011;
import org.example.api.bean.SensorReading;

import java.util.Properties;

/**
 * @author huangqihan
 * @date 2021/2/20
 */
public class SinkToKafka {
    public static void main(String[] args) throws Exception {
        StreamExecutionEnvironment env = StreamExecutionEnvironment.getExecutionEnvironment();
        env.setParallelism(1);

        // listen kafka events
        Properties properties = new Properties();
        properties.setProperty("bootstrap.servers", "localhost:9092");
        DataStreamSource<String> dataStreamSource = env.addSource(new FlinkKafkaConsumer011<>("source", new SimpleStringSchema(), properties));


        SingleOutputStreamOperator<String> mapStream = dataStreamSource.map(line -> {
            String[] fields = line.split(",");
            return new SensorReading(fields[0], new Long(fields[1]), new Double(fields[2])).toString();
        });
        mapStream.print("sink");
        mapStream.addSink(new FlinkKafkaProducer011<>("localhost:9092", "sink", new SimpleStringSchema()));
        env.execute();
    }
}
